// pages/party/party.js
const util = require('../../utils/util.js');
const qiniu = require("../../utils/qiniu.min.js");
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    topic: '',
    maxLength: 16,
    currentLength: 0,
    concern: false,
    text: '关注"一起来往"公众号，及时享受活动提醒服务。',
    userInfo: '',
    act: {
      id: '',
      actType: 1, //聚会
      topic: '',
      actPoster: '/img/temp.png',
      actAddress: '',
      longitude: '',
      latitude: '',
      actStartTime: '',
      actEndTime: '',
      originator: '本人',
      totalCost: '',
      consume: '',
      remark: ''
    }, 
    showStart: false,
    currentStartDate: new Date().getTime(),
    showStartTime: false,
    currentStartTime: util.getTime(new Date()),
    maxStartDate: new Date().getTime(),
    minStartDate: new Date().getTime(),
    showEnd: false,
    currentEndDate: new Date().getTime(),
    showEndTime: false,
    currentEndTime: util.getTime(new Date()),
    maxEndDate: new Date().getTime(),
    remarkStr: '请设置',
    actStartTimeLong: 0,
    actStartTimeStr: '',
    actEndTimeLong: 0,
    actEndTimeStr: '',
    imgUrls: [
      '/img/pic1@2x.png'
    ],
    current: 0,
    btnText: '完成记账'
  },
  deleteArea() {
    this.toggle('act.actAddress', '');
    this.toggle('act.longitude', '');
    this.toggle('act.latitude', '');
  },
  swiperChange(e) {
    this.toggle('act.actPoster', this.data.imgUrls[e.detail.current])
  },
  changeBg() {
    var that = this;
    app.getQiNiuToken(function(res) {
      var qiniuconfig = res;
      wx.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album'],
        success: function(res) {
          const filepath = res.tempFilePaths[0]
          qiniu.upload(filepath, res => {
            var imgList = that.data.imgUrls;
            imgList.push(res.imageURL);
            that.setData({
              current: imgList.length - 1,
              imgUrls: imgList
            });
          }, (error) => {
            console.log('error' + error)
          }, {
            uploadURL: 'https://upload.qiniup.com',
            region: 'ECN',
            domain: qiniuconfig.qiniuDomain,
            uptoken: qiniuconfig.upToken,
          })
        }
      })
    });
  },
  //设置主题
  setTitle() {
    wx.navigateTo({
      url: '/pages/partyTitle/partyTitle?topic=' + this.data.act.topic
    });
  },
  //主题输入
  topicInput(e) {
    var topic = e.detail.value,
      currentLength = e.detail.value.length;
    if (currentLength > this.data.maxLength) {
      wx.showToast({
        title: '输入文字数量已达到上限',
        icon: 'none',
        duration: 2000
      })
      return this.data.topic;
    }
    this.setData({
      topic: topic,
      currentLength: currentLength
    })
  },
  //主题保存
  topicblur(e) {
    var topic = e.detail.value
    if (topic == '') {
      this.setData({
        topic: '好久不见，一起吃个饭吧'
      })
    } else {
      this.setData({
        topic: topic
      })
    }
    this.toggle('act.topic', this.data.topic);
  },
  //开始时间事件
  openStartDate() {
    this.setData({
      showStart: true
    })
  },
  onStartConfirm(event) {
    this.toggle('actStartTimeLong', event.detail)
    this.setData({
      showStartTime: true
    })
  },
  closeStartDate() {
    this.setData({
      showStart: false
    })
  },
  onStartTimeConfirm(event) {
    var time = util.toDate(util.getDate(this.data.actStartTimeLong) + ' ' + event.detail + ':00');
    this.toggle('act.actStartTime', util.formatTime3(time));
    this.toggle('actStartTimeLong', time.getTime());
    this.toggle('actStartTimeStr', util.formatTime4(time));

    var End2Date = new Date(time.getTime());
    End2Date.setFullYear(End2Date.getFullYear() + 1);
    this.setData({
      currentEndDate: time.getTime(),
      currentEndTime: util.getTime(time),
      maxEndDate: End2Date.getTime()
    })
    this.setData({
      showStart: false,
      showStartTime: false
    });
  },
  closeStartTime() {
    this.setData({
      showStartTime: false
    })
  },
  //结束时间事件
  openEndDate() {
    if (this.data.actStartTimeLong > 0) {
      this.setData({
        showEnd: true
      })
    } else {
      wx.showToast({
        title: '请先选择活动开始时间',
        icon: 'none',
        duration: 2000
      })
    }
  },
  onEndConfirm(event) {
    this.toggle('actEndTimeLong', event.detail);
    this.setData({
      showEndTime: true
    })
  },
  closeEndDate() {
    this.setData({
      showEnd: false
    })
  },
  onEndTimeConfirm(event) {
    var time = util.toDate(util.getDate(this.data.actEndTimeLong) + ' ' + event.detail + ':00');
    this.toggle('act.actEndTime', util.formatTime3(time));
    this.toggle('actEndTimeLong', time.getTime());
    this.toggle('actEndTimeStr', util.formatTime4(time));
    this.setData({
      showEnd: false,
      showEndTime: false
    });
  },
  closeEndTime() {
    this.setData({
      showEndTime: false
    })
  },

  /**
* 日历控件绑定函数 
* 点击日期返回
*/
  onPickerChange: function (e) {
    this.setData({
      actStartTime: e.detail.dateString,
      actStartTimeStr: e.detail.dateString,
      actStartTimeLong: new Date(e.detail.dateString).getTime()
    })
    console.log(this.data.actEndTimeStr)
  },
  onPickerChange1: function (e) {
    this.setData({
      actEndTime: e.detail.dateString,
      actEndTimeStr: e.detail.dateString,
      actEndTimeLong: new Date(e.detail.dateString).getTime()
    })
  },

  //聚会地点
  openGPS() {
    var that = this;
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userLocation']) {
          wx.authorize({
            scope: 'scope.userLocation',
            success: function() {
              that.realOpenGPS();
            },
            fail: function(d) {
              wx.showModal({
                title: '获取授权失败',
                content: '是否前往设置允许小程序使用位置信息',
                success(res) {
                  if (res.confirm) {
                    wx.openSetting({
                      complete: function(r) {
                        if (r.authSetting['scope.userLocation']) {
                          that.realOpenGPS();
                        }
                      }
                    });
                  }
                }
              })
            }
          })
        } else {
          that.realOpenGPS();
        }
      }
    });
  },
  realOpenGPS() {
    var that = this;
    wx.chooseLocation({
      success: function(res) {
        that.toggle('act.actAddress', res.name);
        that.toggle('act.longitude', res.longitude);
        that.toggle('act.latitude', res.latitude);
        that.toggle('act.actAddress2', res.address);
      },
      fail(res) {
        console.log(res)
      }
    });
  },
  //设置备注
  setRemark() {
    wx.navigateTo({
      url: '/pages/partyMemo/partyMemo?remark=' + this.data.act.remark
    })
  },
  //设置活动发起人、人均费用、总费用
  setOtherField(e) {
    let key = e.currentTarget.dataset.key,
      title = e.currentTarget.dataset.title,
      value = '';
    if (key == 'act.originator') {
      value = this.data.act.originator;
    } else if (key == 'act.consume') {
      value = this.data.act.consume;
    } else if (key == 'act.totalCost') {
      value = this.data.act.totalCost;
    }
    wx.navigateTo({
      url: '/pages/otherField/otherField?key=' + key + '&title=' + title + '&value=' + value
    })
  },
  invitation() {
    var that = this;
    var data = this.data.act;
    //校验地址、主题、开始结束时间、人均费用必填
    // if (data.topic == '') {
    //   wx.showToast({
    //     title: '请输入活动主题',
    //     icon: 'none',
    //     duration: 2000
    //   })
    //   return;
    // }
    if (that.data.actStartTime == '') {
      wx.showToast({
        title: '请选择开始时间',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    if (that.data.actEndTime == '') {
      wx.showToast({
        title: '请选择结束时间',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    // if (data.actAddress == '') {
    //   wx.showToast({
    //     title: '请选择地点',
    //     icon: 'none',
    //     duration: 2000
    //   })
    //   return;
    // }
    if (!data.consume && data.consume != 0) {
      wx.showToast({
        title: '请填写人均费用',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    //校验开始时间小于结束时间
    if (this.data.actStartTimeLong >= this.data.actEndTimeLong) {
      wx.showToast({
        title: '活动开始时间必须小于活动结束时间',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    //获得选中的背景图
    data.actPoster = this.data.imgUrls[this.data.current];
    //犹豫从T变成了t，只能这样改了，懒得全局替换
    data.actStarttime = that.data.actStartTime + ':00';
    data.actEndtime = that.data.actEndTime + ':00';
    if (data.topic == '') {
      data.topic = '好久不见,一起吃个饭吧!';
    }
    if (data.id == '') {
      this.addAct(data);
    } else {
      this.uptAct(data);
    }
  },
  addAct(actData) {
    app.req({
      url: 'wechat/accountsmanage/save',
      data: actData,
      method: 'POST',
      showLoad: true,
      success: function(res) {
        if (res.code == 200) {
          wx.navigateBack({
            delta: 1
          })
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  uptAct(actData) {
    app.req({
      url: 'wechat/accountsmanage/update',
      data: actData,
      method: 'POST',
      showLoad: true,
      success: function(res) {
        if (res.code == 200) {
          wx.navigateBack({
            delta: 1
          })
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  toggle(type, val) {
    this.setData({
      [type]: val
    });
  },
  //获得默认背景图
  getBgImgList(img) {
    var that = this;
    app.req({
      url: 'wechat/image/list',
      data: {
        "type": 1
      },
      method: 'POST',
      success: function(res) {
        console.log(res)
        if (res.code == 200) {
          var imgList = [],
            current = 0,
            exists = false;
          for (let i in res.data) {
            let item = res.data[i];
            imgList.push(item.url);
            if (item.url == img) {
              current = i;
              exists = true;
            }
          }
          if (img && img != '' && !exists) {
            imgList.push(img);
            current = imgList.length - 1;
          }
          that.setData({
            imgUrls: imgList,
            current: current,
          })
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  //获得活动详情
  getActInfo(id) {
    var that = this;
    app.req({
      url: 'wechat/accountsmanage/info',
      data: {
        "id": id
      },
      method: 'POST',
      success: function(res) {
        if (res.code == 200) {
          var data = res.data,
            startDate = util.formatDate(data.actStarttime),
            endDate = util.formatDate(data.actEndtime);

          var startEndDate = new Date(startDate), End2Date = new Date(endDate);
          startEndDate.setFullYear(startEndDate.getFullYear() + 1);
          End2Date.setFullYear(End2Date.getFullYear() + 1);

          that.setData({
            act: data,
            currentStartDate: startDate,
            currentStartTime: util.getTime(startDate),
            maxStartDate: startEndDate.getTime(),
            currentEndDate: endDate,
            currentEndTime: util.getTime(endDate),
            maxEndDate: End2Date.getTime(),
            remarkStr: data.remark == '' ? '请设置' : util.subRemark(data.remark),
            actStartTimeLong: startDate,
            actStartTimeStr: util.formatTime4(startDate),
            actEndTimeLong: endDate,
            actEndTimeStr: util.formatTime4(endDate),
            btnText: '完成',
            topic: res.data.topic
          });
          that.getBgImgList(data.actPoster);
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  //是否关注公众号
  concernWechat: function() {
    var that = this;
    app.req({
      url: "wechat/sys/register",
      method: "post",
      success: function(res) {
        // that.toggle("concern", !!res);
      }
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    app.getUserInfo(function(userInfo) {
      that.setData({
        userInfo: userInfo
      })
      that.concernWechat();
    })
    if (options.id && options.id != '') {
      this.getActInfo(options.id);
    } else {
      this.getBgImgList();
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var startDate = new Date(), startEndDate = new Date(), startMinDate = new Date();
    startEndDate.setFullYear(startEndDate.getFullYear() + 1);
    startMinDate.setFullYear(startMinDate.getFullYear() - 1);
    this.setData({
      currentStartDate: startDate.getTime(),
      currentStartTime: util.getTime(startDate),
      maxStartDate: startEndDate.getTime(),
      minStartDate: startMinDate.getTime()
    })
  }
})